package com.vehicle.repair.service;

import com.vehicle.repair.model.*;
import com.vehicle.repair.repository.WorkOrderRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class WorkOrderService {
    private final WorkOrderRepository workOrderRepository;
    private final UserService userService;
    private final VehicleService vehicleService;
    private final RepairerService repairerService;

    public WorkOrderService(WorkOrderRepository workOrderRepository, 
                          UserService userService,
                          VehicleService vehicleService,
                          RepairerService repairerService) {
        this.workOrderRepository = workOrderRepository;
        this.userService = userService;
        this.vehicleService = vehicleService;
        this.repairerService = repairerService;
    }

    public WorkOrder createWorkOrder(WorkOrder workOrder, Integer userId, Integer vehicleId) {
        User user = userService.getUserById(userId)
                .orElseThrow(() -> new IllegalArgumentException("User not found"));
        
        Vehicle vehicle = vehicleService.getVehicleById(vehicleId)
                .orElseThrow(() -> new IllegalArgumentException("Vehicle not found"));
        
        workOrder.setUser(user);
        workOrder.setVehicle(vehicle);
        workOrder.setSubmitTime(LocalDateTime.now());
        workOrder.setStatus(WorkOrder.OrderStatus.待分配);
        
        return workOrderRepository.save(workOrder);
    }

    public Optional<WorkOrder> getWorkOrderById(Integer id) {
        return workOrderRepository.findById(id);
    }

    public List<WorkOrder> getWorkOrdersByUser(Integer userId) {
        User user = userService.getUserById(userId)
                .orElseThrow(() -> new IllegalArgumentException("User not found"));
        return workOrderRepository.findByUser(user);
    }

    public List<WorkOrder> getWorkOrdersByStatus(WorkOrder.OrderStatus status) {
        return workOrderRepository.findByStatus(status);
    }

    public WorkOrder updateWorkOrderStatus(Integer orderId, WorkOrder.OrderStatus status) {
        WorkOrder order = workOrderRepository.findById(orderId)
                .orElseThrow(() -> new IllegalArgumentException("Work order not found"));
        
        order.setStatus(status);
        if (status == WorkOrder.OrderStatus.已完成) {
            order.setCompleteTime(LocalDateTime.now());
        }
        
        return workOrderRepository.save(order);
    }

    public void deleteWorkOrder(Integer id) {
        workOrderRepository.deleteById(id);
    }
}
